<template>
   <div class="course-analysis-container">
    <!-- 筛选栏 -->
    <div class="filter-card">
      <div class="filter-header">
        <h3>课程评分分析</h3>
      </div>
      <div class="filter-content">
        <el-select
        
          v-model="query.subId"
          placeholder="请选择课程"
          class="course-select"
          @change="fetchData"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in courseList"
            :key="index"
            :label="item.subName"
            :value="item.subId"
          >
            <span class="option-label">{{ item.subName }}</span>
            <span class="option-id">ID: {{ item.subId }}</span>
          </el-option>
        </el-select>
      </div>
    </div>
        <!-- 图表容器 -->
    <div class="chart-card">
      <div v-loading="loading" class="chart-wrapper">
        <div ref="chart" class="chart-container"></div>
        
        <!-- 空状态 -->
        <div v-if="!scoreData.length" class="empty-state">
          <el-empty description="暂无数据，请选择课程" />
        </div>
      </div>
    </div>
  </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import { getDiff,getSub } from '@/api/txyStudentEvaluation';
  export default {
    data(){
        return{
            loading:false,
            scoreData:[],
            query:{
                subId:''
            },
            courseList:[],
        }
    },
    mounted() {
      this.initCourse();
    },
    methods: {
    async initCourse() {
      try {
        const res = await getSub();
        this.courseList = res.data;
      } catch (error) {
        this.$message.error('课程加载失败');
      }
    },
    async fetchData() {
      if (!this.query.subId) return;
      
      try {
        this.loading = true;
        const res = await getDiff(this.query);
        this.scoreData = res.data;
        this.updateChart();
      } catch (error) {
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    updateChart() {
        // 销毁旧实例
      if (this.chart) {
        this.chart.dispose();
      }
        // 确保DOM元素存在
      if (!this.$refs.chart) return;
        // 初始化新实例
      this.chart = echarts.init(this.$refs.chart);
      window.addEventListener('resize', this.handleResize);


        // 空数据检查
      if (this.scoreData.length === 0) {
        this.chart.showLoading('default', { text: '正在加载数据...' });
        return;
      }
      this.chart.hideLoading();
      const filteredData = this.scoreData.filter(item => item.sumScore >= 10);
      const option = {
        title: {
          text: '课程评分趋势分析',
          left: 'center',
          textStyle: {
            color: '#2c3e50',
            fontSize: 18,
            fontWeight: '600'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#ebeef5',
          borderWidth: 1,
          formatter: params => {
            const data = params[0];
            return `
              <div class="chart-tooltip">
                <div class="tooltip-title">${data.name}</div>
                <div class="tooltip-content">
                  <span class="dot" style="background:${params[0].color}"></span>
                  平均分：<b>${data.value} 分</b>
                </div>
              </div>
            `;
          }
        },
        xAxis: {
          type: 'category',
          data: filteredData.map(item => item.semester),
          axisLabel: {
            rotate: 45,
            color: '#666',
            fontSize: 12
          },
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '平均分',
          min: 0,
          max: 100,
          interval: 10,
          axisLabel: {
            color: '#666',
            formatter: '{value} 分'
          },
          splitLine: {
            lineStyle: {
              color: '#f5f7fa'
            }
          }
        },
        series: [{
          name: '平均分',
          type: 'bar',
          data: filteredData.map(item => item.sumScore),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5b8cff' },
              { offset: 1, color: '#3a6cd9' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              shadowColor: 'rgba(91,140,255,0.5)',
              shadowBlur: 10
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#5b8cff',
            fontWeight: 'bold',
            formatter: '{c} 分'
          }
        }],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '18%',
          containLabel: true
        }
      };

      this.chart.setOption(option,true);
      this.handleResize(); // 立即触发一次resize
    },
    handleResize() {
      this.chart && this.chart.resize();
    }
    },
    beforeDestroy() {
      // 移除所有事件监听
      window.removeEventListener('resize', this.handleResize);
      
      // 彻底销毁图表
      if (this.chart) {
        this.chart.off('click');
        this.chart.dispose();
        this.chart = null;
      }
    }
    };
  </script>
<style lang="scss" scoped>
.course-analysis-container {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

.filter-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  margin-bottom: 24px;
  overflow: hidden;

  .filter-header {
    padding: 16px 24px;
    background: #f8fafc;
    border-bottom: 1px solid #ebeef5;

    h3 {
      margin: 0;
      font-size: 16px;
      color: #2c3e50;
      font-weight: 600;
    }
  }

  .filter-content {
    padding: 24px;
  }
}

.course-select {
  width: 360px;

  ::v-deep .el-input__inner {
    height: 40px;
    border-radius: 8px;
  }
}

.option-label {
  display: block;
  font-size: 14px;
  color: #2c3e50;
}

.option-id {
  font-size: 12px;
  color: #909399;
}

.chart-card {
  min-width: 600px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  overflow: hidden;

  .chart-wrapper {
    position: relative;
    min-height: 500px;
    padding: 24px;
  }

  .chart-container {
    width: 100%;
    height: 500px;
    position: relative; // 新增

      // 确保canvas正确渲染
    canvas {
      display: block !important;
      width: 100% !important;
      height: 100% !important;
    }
  }
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

// 工具提示样式
.chart-tooltip {
  padding: 8px 12px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);

  .tooltip-title {
    color: #2c3e50;
    font-weight: 600;
    margin-bottom: 6px;
  }

  .tooltip-content {
    display: flex;
    align-items: center;
    color: #666;

    .dot {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 8px;
    }
  }
}

@media (max-width: 768px) {
  .course-select {
    width: 100%;
  }

  .chart-container {
    height: 400px;
  }
}
</style>